import usePictureTagCategory from '@/hooks/usePictureTagCategory';
import CreateModal from '@/pages/Admin/Picture/components/CreateModal';
import ReviewModal from '@/pages/Admin/Picture/components/ReviewModal';
import UpdateModal from '@/pages/Admin/Picture/components/UpdateModal';
import {
  deletePictureUsingPost,
  listPictureVoByPageUsingPost,
} from '@/services/backend/pictureController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, Dropdown, Image, MenuProps, message, Select, Space, Tag, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import UpdatePictureModal from "@/components/UpdatePictureModal";
import CreatePictureModal from "@/pages/My/components/CreatePictureModal";

/**
 * 用户管理页面
 *
 * @constructor
 */
const PictureAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const [reviewModalVisible, setReviewModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.PictureVO>();
  const { tagList, categoryList } = usePictureTagCategory();
  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.PictureVO) => {
    const hide = message.loading('正在删除');
    const ids: string[] = [row.id as any];
    const batchDeleteRequest: API.BatchDeleteRequest = {
      ids,
    };
    if (!row) return true;
    try {
      await deletePictureUsingPost(batchDeleteRequest);
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };
  const updateMenu: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <a
          target="_blank"
          rel="noopener noreferrer"
          onClick={() => {
            setCreateModalVisible(true);
          }}
        >
          修改图片
        </a>
      ),
    },
    {
      key: '2',
      label: (
        <a
          target="_blank"
          rel="noopener noreferrer"
          onClick={() => {
            setUpdateModalVisible(true);
          }}
        >
          修改信息
        </a>
      ),
    },
  ];

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.PictureVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '图片',
      hideInSearch: true,
      dataIndex: 'url',
      valueType: 'image',
      renderFormItem(_, record) {
        return (
          <div
            style={{
              display: 'flex',
              flexDirection: 'column', // 垂直排列
              justifyContent: 'center', // 垂直居中
              alignItems: 'center', // 水平居中
              gap: 10,
            }}
          >
            <Image src={record.value} alt={record.value} width={100} height={100} />
          </div>
        );
      },
    },
    {
      title: '图片名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '分类',
      dataIndex: 'category',
      valueType: 'text',
      renderFormItem(schema) {
        const { fieldProps } = schema;

        //@ts-ignore
        return (
          <Select
            options={categoryList?.map((item) => {
              return {
                label: item,
                value: item,
              };
            })}
            {...fieldProps}
          />
        );
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      renderFormItem(schema) {
        const { fieldProps } = schema;
        //@ts-ignore
        return (
          <Select
            options={tagList?.map((item) => {
              return {
                label: item,
                value: item,
              };
            })}
            {...fieldProps}
            mode="tags"
          />
        );
      },
      render(_, record) {
        if (!record.tags) {
          return <></>;
        }
        return record.tags.map((tag) => {
          return (
            <Tag style={{ marginBottom: 10 }} key={tag}>
              {tag}
            </Tag>
          );
        });
      },
    },
    {
      title: '简介',
      dataIndex: 'introduction',
      valueType: 'textarea',
      ellipsis: true,
    },
    {
      title: '格式',
      dataIndex: 'picFormat',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '高度',
      dataIndex: 'picHeight',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '宽度',
      dataIndex: 'picWidth',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '宽高比',
      dataIndex: 'picScale',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '大小',
      dataIndex: 'picSize',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '审核状态',
      dataIndex: 'reviewStatus',
      valueType: 'select',
      hideInForm: false,
      valueEnum: {
        0: {
          text: '待审核',
          status: 'Processing',
        },
        1: {
          text: '通过',
          status: 'Success',
        },
        2: {
          text: '拒绝',
          status: 'Error',
        },
      },
    },
    {
      title: '审核信息',
      dataIndex: 'reviewMessage',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Dropdown
            onOpenChange={() => {
              setCurrentRow(record);
            }}
            menu={{ items: updateMenu }}
          >
            <a>
              <Space>修改</Space>
            </a>
          </Dropdown>
          <Typography.Link
            type="danger"
            onClick={() => {
              setCurrentRow(record);
              setReviewModalVisible(true);
            }}
          >
            审核
          </Typography.Link>
          <Typography.Link type="danger" onClick={() => handleDelete(record)}>
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];
  return (
    <div>
      <ProTable<API.PictureVO>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 上传图片
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField: any = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          console.log(filter)
          const { data, code } = await listPictureVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.PictureQueryRequest);
          console.log(params, sort, filter);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      <CreatePictureModal
        id={currentRow?.id}
        visible={createModalVisible}
        onSubmit={() => {
          setCreateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdatePictureModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
      <ReviewModal
        visible={reviewModalVisible}
        data={currentRow}
        onSubmit={() => {
          setReviewModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setReviewModalVisible(false);
        }}
      />
    </div>
  );
};
export default PictureAdminPage;
